﻿using Microsoft.Phone.Net.NetworkInformation;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows.Resources;

namespace BingImageManager
{
  public  class BingImageManager
    {

        private readonly BingApi _bingApi = new BingApi();
        private Action<string> _callback;
        //Config Begin
        private String _resolution;
        private String _savePath;
        private String _localPath;
        //Config End

        public void GetBingImageWithCallBack(Action<string> callback)
        {
            if (!NetworkInterface.GetIsNetworkAvailable()) return;
            _callback = callback;
            try
            {   
                _bingApi.Init(DownloadImage);
            }
            catch (WebException e)
            {
                Debug.WriteLine("网络连接失败，请连接网络后重试。"+e.Message);
            }
            catch (Exception e)
            {
                Debug.WriteLine("程序运行发生异常：" + e.Message);
            }
        }

        void DownloadImage()
        {
            String imgUrl = _bingApi.GetImageUrl(_resolution);
            _localPath = Path.Combine(_savePath, DateTime.Today.ToString("u").Substring(0,10) + Path.GetFileName(_bingApi.GetImageUrl(_resolution)));
            Debug.WriteLine("开始下载" + imgUrl + "到" + _localPath);

                WebClient client = new WebClient();
                try
                {
                    client.OpenReadCompleted += client_OpenReadCompleted;
                    client.OpenReadAsync(new Uri(imgUrl, UriKind.Absolute), client);
                }
                catch (WebException e)
                {
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        Debug.WriteLine("下载指定分辨率" + _resolution + "图片失败，开始尝试下载默认分辨率图片...");
                        imgUrl = _bingApi.GetImageUrl();
                        Debug.WriteLine("开始下载" + imgUrl + "到" + _localPath);
                        client.OpenReadAsync(new Uri(imgUrl, UriKind.Absolute), client);
                    }
                    else
                    {
                        throw;
                    }
            }
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            using (IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var resInfo = new StreamResourceInfo(e.Result, null);
                var reader = new StreamReader(resInfo.Stream);
                byte[] contents;
                using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
                {
                    contents = bReader.ReadBytes((int)reader.BaseStream.Length);
                }
                if (MyStore.FileExists(_localPath))
                {
                    MyStore.DeleteFile(_localPath);
                }
                using (IsolatedStorageFileStream stream = MyStore.CreateFile(_localPath))
                {

                    stream.Write(contents, 0, contents.Length);
                }
            }
            Debug.WriteLine("下载图片成功");
            _callback.Invoke(_localPath);
        }
      /// <summary>
      /// 由于需要在主线程中获取设备屏幕信息，
      /// 所以不能放入其他线程中，采取先单独调用init。
      /// </summary>
        public void InitConfig()
        {
            Debug.WriteLine("开始读取配置文件");

            _bingApi.Time = 0;
            _bingApi.Location = "zh-CN";
            switch (ResolutionHelper.CurrentResolution)
            {
                case Resolutions.WVGA:
                    _resolution = "480x800";
                    break;
                case Resolutions.WXGA:
                    _resolution = "768x1280";
                    break;
                case Resolutions.HD720p:
                    _resolution = "720x1280";
                    break;
                default:
                    _resolution = "480x800";
                    break;
            }
            _savePath = "CacheFolder";

            Debug.WriteLine("读取配置成功");
        }
    }
}
